package com.csu.letaobackend.controllerM;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.csu.letaobackend.bean.Admin;
import com.csu.letaobackend.bean.User;
import com.csu.letaobackend.commom.CommonResponse;
import com.csu.letaobackend.service.UserService;
import com.csu.letaobackend.serviceM.AdminMService;
import com.csu.letaobackend.serviceM.SellerMService;
import com.csu.letaobackend.serviceM.UserMService;
import com.csu.letaobackend.util.FaceSpot;
import com.csu.letaobackend.vo.SellerVO;
import com.csu.letaobackend.vo.UserVO;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
@CrossOrigin
@RequestMapping("/admin/account")
public class AccountMController {

      @Autowired
      UserMService userMService;

      @Autowired
      SellerMService sellerMService;

      @Autowired
      AdminMService adminMService;

      @GetMapping("/users/pages/{pagesize}/{pageid}")
      @ResponseBody
      public CommonResponse<IPage<UserVO>> getAllUsers(@PathVariable int pageid, @PathVariable int pagesize) {
            return userMService.getAllUsers(pageid, pagesize);
      }

      @GetMapping("/users/{username}/pages/{pagesize}/{pageid}")
      @ResponseBody
      public CommonResponse<IPage<UserVO>> searchUser(@PathVariable String username,
                                                      @PathVariable int pageid, @PathVariable int pagesize) {
            return userMService.searchUser(username, pageid, pagesize);
      }

      @PutMapping("/users/{username}")
      @ResponseBody
      public CommonResponse updateUser(@PathVariable String username, @RequestParam int available) {
            return userMService.updateAvailable(username, available);
      }

      @DeleteMapping("/users/{username}")
      @ResponseBody
      public CommonResponse deleteUser(@PathVariable String username) {
            return userMService.deleteUser(username);
      }

      @GetMapping("/sellers/pages/{pagesize}/{pageid}")
      @ResponseBody
      public CommonResponse<IPage<SellerVO>> getAllSellers(@PathVariable int pageid, @PathVariable int pagesize) {
            return sellerMService.getAllSellers(pageid, pagesize);
      }

      @GetMapping("/sellers/{username}/pages/{pagesize}/{pageid}")
      @ResponseBody
      public CommonResponse<IPage<SellerVO>> searchSeller(@PathVariable String username,
                                                          @PathVariable int pageid, @PathVariable int pagesize) {
            return sellerMService.searchSeller(username, pageid, pagesize);
      }

      @PutMapping("/sellers/{username}")
      @ResponseBody
      public CommonResponse updateAvailable(@PathVariable String username, @RequestParam int available) {
            return sellerMService.updateAvailable(username, available);
      }

      @DeleteMapping("/sellers/{username}")
      @ResponseBody
      public CommonResponse deleteSeller(@PathVariable String username) {
            return sellerMService.deleteSeller(username);
      }


      @PostMapping("/admins/login")
      @ResponseBody
      public CommonResponse<Admin> login(@RequestParam String adminname, @RequestParam String password, HttpSession session) {
            CommonResponse<Admin> response = adminMService.getAdmin(adminname, password);
            if (response.isSuccess()) {
                  session.setAttribute("login_admin", response.getData());
            }
            return response;
      }


      @PostMapping("/admins/logout")
      @ResponseBody
      public CommonResponse<String> logout(HttpSession session) {
            Admin login_admin = (Admin) session.getAttribute("login_admin");
            if (login_admin != null) {
                  session.removeAttribute("login_admin");
                  return CommonResponse.createForSuccessMessage("退出登录成功");
            }
            return CommonResponse.createForError("管理员未登录，不能退出");
      }

      @PostMapping("/admins/register")
      @ResponseBody
      public CommonResponse<Admin> register(@RequestBody Admin admin, HttpSession session) {

            CommonResponse<Admin> response = adminMService.registerAdmin(admin);
            if (response.isSuccess()) {
                  session.setAttribute("login_admin", response.getData());
            }
            return response;
      }

      @GetMapping("/admins/homepage")
      @ResponseBody
      public CommonResponse<Admin> getAdmin(HttpSession session) {
            Admin login_admin = (Admin) session.getAttribute("login_admin");
            if (login_admin == null)
                  return CommonResponse.createForSuccessMessage("没有管理员登录");

            return adminMService.getAdmin(login_admin.getAdminname());
      }


      @PutMapping("/admins/homepage")
      @ResponseBody
      CommonResponse<Admin> updateAdmin(@RequestBody Admin admin, HttpSession session) {
            return adminMService.updateAdmin(admin);
      }

      @PostMapping("/admins/password")
      @ResponseBody
      CommonResponse<Admin> updateAdminPassword(@RequestParam String username, @RequestParam String newPassword, HttpSession session) {
            return adminMService.updateAdminPassword(username, newPassword);
      }


      @PostMapping("/admins/facetest")
      @ResponseBody
      CommonResponse<Admin> facetest(HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException, JSONException {


            request.setCharacterEncoding("UTF-8");
            String img = request.getParameter("img");

            JSONObject js = FaceSpot.searchFace(img, "1000", "xa");
            JSONArray user_list = null;
            try {
                  user_list = js.getJSONObject("result").getJSONArray("user_list");
                  System.out.println(js.getJSONObject("result").getJSONArray("user_list"));
            } catch (JSONException e) {
                  return CommonResponse.createForError(js.getString("error_msg"));
            }

            double testScore = user_list.getJSONObject(0).getDouble("score");
            String username = user_list.getJSONObject(0).getString("user_id");

            System.out.println(testScore);
            System.out.println(username);
            Admin admin = adminMService.getAdmin(username).getData();
            if( testScore > 90){
                  session.setAttribute("login_admin", admin);
                  return CommonResponse.createForSuccess(admin);

            } else {
                  return CommonResponse.createForError("未能在图片库寻找到信息");
            }
      }


}
